/**
 * Created by showtan on 2018/12/27.
 * 通知列表
 */

import { ScrollView } from 'react-native-mjrefresh';
let currentPage = 1;
let showCount = 10;
let isFirstLoad = true; // 第一次加载
let isLoading = true;
let isRefreshing = false;
let isLoadMore = false;


class MinePage extends Component {

  static navigationOptions = ({ navigation }) => ({
    tabBarOnPress: (e) => {
      DeviceEventEmitter.emit('messageNumUpdate', 11111); // 监听变化更新
      navigation.navigate('Message', {}); // 需跳转  否则无法切换
    }
  });

  constructor(props) {
    super(props);
    this.state = {
      data: ['row 1', 'row 2', 'row 3', 'row 4', 'row 5', 'row 6', 'row 7', 'row 8'],
      text: '下拉刷新',
      showSwiper: true
    }
  }

  /**
   * 数据加载
   * @param {分页} currentPage 
   * @param {每页条数} showCount 
   * @param {正在加载} isLoading 
   * @param {下拉刷新} isRefreshing 
   * @param {加载更多} isLoadMore 
   */
  _loadData(currentPage, isLoading, isRefreshing, isLoadMore) {
    let params = {
      showCount: showCount,
      currentPage: currentPage,
      isLoading: isLoading,
      isRefreshing: isRefreshing,
      isLoadMore: isLoadMore
    };
    // this.props.dispatch({ type: 'task/taskList', payload: params });
  }

  componentDidMount() {
    DeviceEventEmitter.addListener('messageNumUpdate', (val) => this.props.dispatch({ type: 'task/changeNum', payload: { num: 0 } })); // 监听
    currentPage = 1; isFirstLoad = true;
    InteractionManager.runAfterInteractions(() => {
      this._loadData(currentPage, isLoading, isRefreshing, isLoadMore);
      this.props.task.isLoading = true;
    });
  }

  _onEndReach = () => { // 加载更多 
    global.consoleLog && console.log(isFirstLoad)
    if (!isFirstLoad && (currentPage == this.props.task.currentPage)) {
      currentPage += 1;
      global.consoleLog && console.log(this.props.task, this.props.task.isLoadMore)
      if (this.props.task.isLoadMore) {
        this._loadData(currentPage, !isLoading, isRefreshing, !isLoadMore);
      }
    }
  }

  _onRefresh = () => { // 下拉刷新
    currentPage = 1; //初始化到第一页
    this._loadData(currentPage, !isLoading, !isRefreshing, isLoadMore);
    setTimeout(() => {
      this._hw && this._hw.finishRefresh()
    }, 1500)
  }

  _renderFooter = () => { // 底部
    return (
      (this.props.task.total > showCount * currentPage && this.props.task.isLoadMore) ?
        <StaticContainer>
          <LoadMoreFooter />
        </StaticContainer> : <View style={{ justifyContent: 'center', alignItems: 'center', marginVertical: adapt(6) }}>
          <Text style={{ color: '#626262' }}>没有更多任务了!</Text>
        </View>
    )
  }

  // shouldComponentUpdate(nextProps, nextState) {
  //   return this.state.index !== nextState.index;
  // }

  componentDidUpdate() {
    const { task } = this.props;
    if (task.list_status == 0) {
      task.list_status = -1; this._hw && this._hw.finishRefresh();
    } else if (task.list_status == 1) {
      task.list_status = -1; Toast.info(task.backMessage);
    }
  }

  _delete = (data, value) => {
    Toast.success(`${value == 1 ? '已标记为已读' : '删除'}成功`);
    this.setState({ showSwiper: false });
    this.timer = setTimeout(() => { this.setState({ showSwiper: true }); }, 500);
  }

  componentWillUnmount() {
    this.timer && clearTimeout(this.timer);
  }

  render() {
    return (
      <View style={styles.container}>
        {/* <SwipeListView
          useFlatList
          data={this.state.data}
          extraData={this.state}
          renderItem={this._renderItem}
          ListFooterComponent={this._renderFooter}
          onEndReachedThreshold={.1}
          refreshing={false}
          onEndReached={this._onEndReach}
          onRefresh={this._onRefresh}
          keyExtractor={(item, index) => index.toString()}
          renderHiddenItem={(data, rowMap) => (
            (this.state.showSwiper) && <View style={styles.action}>
              <TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnLeft]} onPress={() => this._delete(data, 1)}>
                <Text style={{ color: '#fff', fontWeight: '600' }}>已读</Text>
              </TouchableOpacity>
              <TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]} onPress={() => this._delete(data, 2)}>
                <Text style={{ color: '#fff', fontWeight: '600' }}>删除</Text>
              </TouchableOpacity>
            </View>
          )}
          leftOpenValue={0}
          rightOpenValue={-120}
          renderScrollComponent={props => <ScrollView style={{ flex: 1 }}
            refreshControl={<RefreshControlComponent ref={ref => this._hw = ref} onRefresh={this._onRefresh} />}
          />}
        /> */}
        <View style={{ flexDirection: 'row' }}>
          <Text>消息推送所需cid：</Text>
          <Text selectable={true}>{YXStorage.get('cid').cid}</Text>
        </View>
      </View>
    );
  }

  _renderItem = ({ item }) => {
    return (
      <TouchableOpacity onPress={() => this.props.navigation.navigate('MessageDetail', {})} activeOpacity={1} style={styles.itemCell}>
        <Image style={{ width: adapt(32), height: adapt(32), marginRight: adapt(20) }} source={Images.other.icon_messages} />
        <View style={{ width: width - adapt(95), justifyContent: 'center' }}>
          <Text style={{ fontSize: adapt(16), color: '#000' }}>更新软件</Text>
          <View style={styles.bottomCellStyle}>
            <View style={{ borderRadius: adapt(4), overflow: 'hidden' }}>
              <Text style={styles.tastStatus}>发给：all</Text>
            </View>
            <Text style={{ fontSize: adapt(12), color: '#e2e2e2' }}>2019-01-14 16:51:12</Text>
          </View>
        </View>
      </TouchableOpacity>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ededed',
    justifyContent: 'center',
    alignItems: 'center'
  },
  itemCell: {
    paddingHorizontal: adapt(20),
    paddingVertical: adapt(16),
    flexDirection: 'row',
    alignItems: 'center',
    borderTopWidth: adapt(1),
    borderColor: '#eee',
    backgroundColor: '#fff'
  },
  tastStatus: {
    backgroundColor: themeColor,
    paddingHorizontal: adapt(4),
    paddingTop: adapt(2),
    paddingBottom: adapt(1.5),
    color: '#fff'
  },
  bottomCellStyle: {
    flexDirection: 'row',
    marginTop: adapt(10),
    justifyContent: 'space-between',
    alignItems: 'center'
  },

  action: {
    alignItems: 'center',
    backgroundColor: themeColor,
    flex: 1,
    flexDirection: 'row',
    padding: adapt(15)
  },
  backRightBtn: {
    alignItems: 'center',
    bottom: 0,
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    width: adapt(60)
  },
  backRightBtnLeft: {
    backgroundColor: '#FABC3C',
    right: adapt(60)
  },
  backRightBtnRight: {
    backgroundColor: '#FF773D',
    right: 0
  },
});

MinePage.proptypes = {
  task: PropTypes.object,
  dispatch: PropTypes.func
}

function mapStateToProps({ task }) {
  return { task }
}

export default connect(mapStateToProps)(MinePage)